import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//  https://leetcode.cn/problems/3sum/
public class ThreeSum {
    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {



            Arrays.sort(nums);
            List<List<Integer>> res = new ArrayList<>();

            for(int i = 0 ; i < nums.length -2  ; i ++){
                if(nums[i] > 0) return res;
                if(i > 0 && nums[i] == nums[i-1]) continue;
                int left = i + 1;
                int right = nums.length - 1;
                while(left < right)
                {
                    if(nums[left] + nums[right] + nums[i] > 0) {
                        right --;
                    }else if(nums[left] + nums[right] + nums[i] < 0){
                        left ++;
                    }else{
                        List<Integer> tmp = new ArrayList<>();
                        tmp.add(nums[i]);
                        tmp.add(nums[left]);
                        tmp.add(nums[right]);
                        res.add(tmp);
                        while(left < right && nums[right] == nums[right-1] )right--;
                        while(left < right && nums[left] == nums[left+1] )left++;
                        right--;
                        left ++;
                    }

                }
            }
            return res;




        }
    }
}
